package barcan.flutter.io.image_picker.statusbar;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Locale;

/*
 * created by wdlmm1214
 * on 2020/1/9
 */public class QMUIDisplayHelper {
    public static final float DENSITY;
    private static final String TAG = "QMUIDisplayHelper";
    private static Boolean sHasCamera;
    private static int[] sPortraitRealSizeCache;
    private static int[] sLandscapeRealSizeCache;
    private static final String VIVO_NAVIGATION_GESTURE = "navigation_gesture_on";
    private static final String HUAWAI_DISPLAY_NOTCH_STATUS = "display_notch_status";

    public QMUIDisplayHelper() {
    }

    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((WindowManager)context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    public static int dpToPx(int dpValue) {
        return (int)((float)dpValue * DENSITY + 0.5F);
    }

    public static int pxToDp(float pxValue) {
        return (int)(pxValue / DENSITY + 0.5F);
    }

    public static float getDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    public static float getFontDensity(Context context) {
        return context.getResources().getDisplayMetrics().scaledDensity;
    }

    public static int getScreenWidth(Context context) {
        return getDisplayMetrics(context).widthPixels;
    }

    public static int getScreenHeight(Context context) {
        return getDisplayMetrics(context).heightPixels;
    }

    public static int[] getRealScreenSize(Context context) {
        if (QMUIDeviceHelper.isEssentialPhone() && Build.VERSION.SDK_INT >= 26) {
            return doGetRealScreenSize(context);
        } else {
            int orientation = context.getResources().getConfiguration().orientation;
            if (orientation == 2) {
                if (sLandscapeRealSizeCache == null) {
                    sLandscapeRealSizeCache = doGetRealScreenSize(context);
                }

                return sLandscapeRealSizeCache;
            } else {
                if (sPortraitRealSizeCache == null) {
                    sPortraitRealSizeCache = doGetRealScreenSize(context);
                }

                return sPortraitRealSizeCache;
            }
        }
    }

    private static int[] doGetRealScreenSize(Context context) {
        int[] size = new int[2];
        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);
        int widthPixels = metrics.widthPixels;
        int heightPixels = metrics.heightPixels;

        try {
            widthPixels = (Integer)Display.class.getMethod("getRawWidth").invoke(d);
            heightPixels = (Integer)Display.class.getMethod("getRawHeight").invoke(d);
        } catch (Exception var9) {
        }

        if (Build.VERSION.SDK_INT >= 17) {
            try {
                Point realSize = new Point();
                d.getRealSize(realSize);
                Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
                widthPixels = realSize.x;
                heightPixels = realSize.y;
            } catch (Exception var8) {
            }
        }

        size[0] = widthPixels;
        size[1] = heightPixels;
        return size;
    }

    public static int getUsefulScreenWidth(Activity activity) {
        return getUsefulScreenWidth(activity, QMUINotchHelper.hasNotch(activity));
    }

    public static int getUsefulScreenWidth(View view) {
        return getUsefulScreenWidth(view.getContext(), QMUINotchHelper.hasNotch(view));
    }

    public static int getUsefulScreenWidth(Context context, boolean hasNotch) {
        int result = getRealScreenSize(context)[0];
        int orientation = context.getResources().getConfiguration().orientation;
        boolean isLandscape = orientation == 2;
        if (!hasNotch) {
            if (isLandscape && QMUIDeviceHelper.isEssentialPhone() && Build.VERSION.SDK_INT < 26) {
                result -= 2 * StatusBarHelper.getStatusbarHeight(context);
            }

            return result;
        } else {
            if (isLandscape) {
                if (QMUIDeviceHelper.isHuawei() && !huaweiIsNotchSetToShowInSetting(context)) {
                    result -= QMUINotchHelper.getNotchSizeInHuawei(context)[1];
                }

                if (QMUIDeviceHelper.isXiaomi() && !xiaomiIsNotchSetToShowInSetting(context)) {
                    result -= QMUINotchHelper.getNotchHeightInXiaomi(context);
                }
            }

            return result;
        }
    }

    public static int getUsefulScreenHeight(Activity activity) {
        return getUsefulScreenHeight(activity, QMUINotchHelper.hasNotch(activity));
    }

    public static int getUsefulScreenHeight(View view) {
        return getUsefulScreenHeight(view.getContext(), QMUINotchHelper.hasNotch(view));
    }

    private static int getUsefulScreenHeight(Context context, boolean hasNotch) {
        int result = getRealScreenSize(context)[1];
        int orientation = context.getResources().getConfiguration().orientation;
        boolean isPortrait = orientation == 1;
        if (!hasNotch) {
            if (isPortrait && QMUIDeviceHelper.isEssentialPhone() && Build.VERSION.SDK_INT < 26) {
                result -= 2 * StatusBarHelper.getStatusbarHeight(context);
            }

            return result;
        } else {
            if (isPortrait && QMUIDeviceHelper.isXiaomi() && !xiaomiIsNotchSetToShowInSetting(context)) {
                result -= QMUINotchHelper.getNotchHeightInXiaomi(context);
            }

            return result;
        }
    }

    public static boolean isNavMenuExist(Context context) {
        boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap.deviceHasKey(4);
        return !hasMenuKey && !hasBackKey;
    }

    public static int dp2px(Context context, int dp) {
        return (int)((double)(getDensity(context) * (float)dp) + 0.5D);
    }

    public static int sp2px(Context context, int sp) {
        return (int)((double)(getFontDensity(context) * (float)sp) + 0.5D);
    }

    public static int px2dp(Context context, int px) {
        return (int)((double)((float)px / getDensity(context)) + 0.5D);
    }

    public static int px2sp(Context context, int px) {
        return (int)((double)((float)px / getFontDensity(context)) + 0.5D);
    }

    public static boolean hasStatusBar(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity)context;
            WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
            return (attrs.flags & 1024) != 1024;
        } else {
            return true;
        }
    }

    public static int getActionBarHeight(Context context) {
        int actionBarHeight = 0;
        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(16843499, tv, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
        }

        return actionBarHeight;
    }

    public static int getStatusBarHeight(Context context) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception var6) {
            var6.printStackTrace();
            return 0;
        }
    }

    public static int getNavMenuHeight(Context context) {
        if (!isNavMenuExist(context)) {
            return 0;
        } else {
            int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
            return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : getRealScreenSize(context)[1] - getScreenHeight(context);
        }
    }

    public static final boolean hasCamera(Context context) {
        if (sHasCamera == null) {
            PackageManager pckMgr = context.getPackageManager();
            boolean flag = pckMgr.hasSystemFeature("android.hardware.camera.front");
            boolean flag1 = pckMgr.hasSystemFeature("android.hardware.camera");
            boolean flag2 = flag || flag1;
            sHasCamera = flag2;
        }

        return sHasCamera;
    }

    public static boolean hasHardwareMenuKey(Context context) {
        boolean flag;
        if (Build.VERSION.SDK_INT < 11) {
            flag = true;
        } else if (Build.VERSION.SDK_INT >= 14) {
            flag = ViewConfiguration.get(context).hasPermanentMenuKey();
        } else {
            flag = false;
        }

        return flag;
    }

    @SuppressLint({"MissingPermission"})
    public static boolean hasInternet(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

    public static boolean isPackageExist(Context context, String pckName) {
        try {
            PackageInfo pckInfo = context.getPackageManager().getPackageInfo(pckName, 0);
            if (pckInfo != null) {
                return true;
            }
        } catch (PackageManager.NameNotFoundException var3) {
        }

        return false;
    }

    public static boolean isSdcardReady() {
        return "mounted".equals(Environment.getExternalStorageState());
    }

    public static String getCurCountryLan(Context context) {
        Configuration config = context.getResources().getConfiguration();
        Locale sysLocale;
        if (Build.VERSION.SDK_INT >= 24) {
            sysLocale = config.getLocales().get(0);
        } else {
            sysLocale = config.locale;
        }

        return sysLocale.getLanguage() + "-" + sysLocale.getCountry();
    }

    public static boolean isZhCN(Context context) {
        Configuration config = context.getResources().getConfiguration();
        Locale sysLocale;
        if (Build.VERSION.SDK_INT >= 24) {
            sysLocale = config.getLocales().get(0);
        } else {
            sysLocale = config.locale;
        }

        String lang = sysLocale.getCountry();
        return lang.equalsIgnoreCase("CN");
    }

    public static void setFullScreen(Activity activity) {
        Window window = activity.getWindow();
        window.addFlags(512);
        window.addFlags(1024);
    }

    public static void cancelFullScreen(Activity activity) {
        Window window = activity.getWindow();
        window.clearFlags(1024);
        window.clearFlags(512);
    }

    public static boolean isFullScreen(Activity activity) {
        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
        return (params.flags & 1024) == 1024;
    }

    public static boolean isElevationSupported() {
        return Build.VERSION.SDK_INT >= 21;
    }

    public static boolean hasNavigationBar(Context context) {
        boolean hasNav = deviceHasNavigationBar();
        if (!hasNav) {
            return false;
        } else {
            return QMUIDeviceHelper.isVivo() ? vivoNavigationGestureEnabled(context) : true;
        }
    }

    private static boolean deviceHasNavigationBar() {
        boolean haveNav = false;

        try {
            Class<?> windowManagerGlobalClass = Class.forName("android.view.WindowManagerGlobal");
            Method getWmServiceMethod = windowManagerGlobalClass.getDeclaredMethod("getWindowManagerService");
            getWmServiceMethod.setAccessible(true);
            Object iWindowManager = getWmServiceMethod.invoke((Object)null);
            Class<?> iWindowManagerClass = iWindowManager.getClass();
            Method hasNavBarMethod = iWindowManagerClass.getDeclaredMethod("hasNavigationBar");
            hasNavBarMethod.setAccessible(true);
            haveNav = (Boolean)hasNavBarMethod.invoke(iWindowManager);
        } catch (Exception var6) {
            var6.printStackTrace();
        }

        return haveNav;
    }

    public static boolean vivoNavigationGestureEnabled(Context context) {
        int val = Settings.Secure.getInt(context.getContentResolver(), "navigation_gesture_on", 0);
        return val != 0;
    }

    public static boolean huaweiIsNotchSetToShowInSetting(Context context) {
        int result = Settings.Secure.getInt(context.getContentResolver(), "display_notch_status", 0);
        return result == 0;
    }

    @TargetApi(17)
    public static boolean xiaomiIsNotchSetToShowInSetting(Context context) {
        return Settings.Global.getInt(context.getContentResolver(), "force_black", 0) == 0;
    }

    static {
        DENSITY = Resources.getSystem().getDisplayMetrics().density;
        sHasCamera = null;
        sPortraitRealSizeCache = null;
        sLandscapeRealSizeCache = null;
    }
}
